using Autofac;
using Autofac.Extensions.DependencyInjection;
using CoreManager.API.Configuration;
using CoreManager.Core.Extensions;
using CoreManager.Core.Logging;
using CoreManager.Repository.DbContext;
using CoreManager.Models.Mappings;
using Microsoft.EntityFrameworkCore;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// 配置Serilog - 替换默认日志提供者
Log.Logger = SerilogConfiguration
    .ConfigureSerilog(builder.Configuration, builder.Environment)
    .CreateLogger();

// 清除默认日志提供者，只使用Serilog
builder.Logging.ClearProviders();
builder.Host.UseSerilog(Log.Logger, dispose: true);

// 配置Autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
    // 注册主模块
    containerBuilder.RegisterModule(new DependencyInjectionModule(builder.Configuration));
    
    // 注册条件模块
    containerBuilder.RegisterModule(new ConditionalModule(builder.Configuration));
    
    // 注册环境特定模块
    containerBuilder.RegisterModule(new EnvironmentModule(builder.Environment.EnvironmentName));
});

// 配置JSON序列化选项（包含控制器配置）
builder.Services.ConfigureJsonOptions();

// 添加HttpContextAccessor
builder.Services.AddHttpContextAccessor();

// 添加AutoMapper配置
builder.Services.AddAutoMapper(typeof(MenuMappingProfile), typeof(RoleMappingProfile));

// 添加缓存服务
builder.Services.AddCacheService(builder.Configuration);

// 配置EF Core
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<CoreManagerDbContext>(options =>
{
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
    
    // 开发环境启用敏感数据记录
    if (builder.Environment.IsDevelopment())
    {
        options.EnableSensitiveDataLogging();
        options.EnableDetailedErrors();
    }
});

// 配置自定义数据库日志
builder.Services.ConfigureDatabaseLogging();

// 添加自定义服务
builder.Services
    .AddJwtAuthentication(builder.Configuration)
    .AddSwaggerDocumentation()
    .AddCorsPolicy(builder.Configuration)
    .AddRedisCache(builder.Configuration);

var app = builder.Build();

try
{
    Log.Information("正在启动 CoreManager API...");

    // 配置中间件管道
    app.ConfigureMiddlewarePipeline(app.Environment);

    // 配置Swagger文档
    app.UseSwaggerDocumentation(app.Environment);

    // 初始化数据库
    using (var scope = app.Services.CreateScope())
    {
        var context = scope.ServiceProvider.GetRequiredService<CoreManagerDbContext>();
        await context.InitializeDatabaseAsync();
    }

    // 映射控制器
    app.MapControllers();

    Log.Information("CoreManager API 启动成功，监听端口: {Urls}", string.Join(", ", app.Urls));
    
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "CoreManager API 启动失败");
    throw;
}
finally
{
    Log.CloseAndFlush();
}